package dbutils

import (
	"database/sql"
	"fmt"

	"github.com/go-sql-driver/mysql"
	_ "github.com/go-sql-driver/mysql"
)

func Init(config DbConfig) (*sql.DB, error) {
	db, err := getDatabase(config)
	if err != nil {
		return nil, err
	}
	//创建表
	_, err = db.Exec(UserTable)
	if err != nil {
		return nil, err
	}
	return db, nil
}

type DbConfig struct {
	SqlName         string
	SqlPwd          string
	SqlAddress      string
	SqlPort         string
	SqlDatabaseName string
}

func (config DbConfig) getDataSourceName() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", config.SqlName, config.SqlPwd, config.SqlAddress, config.SqlPort, config.SqlDatabaseName)
}
func (config DbConfig) getDataSource() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/", config.SqlName, config.SqlPwd, config.SqlAddress, config.SqlPort)
}

/**
获取数据库的链接,如果不存在,就会创建
 */
func getDatabase(config DbConfig) (*sql.DB, error) {
	db, err := sql.Open("mysql", config.getDataSourceName())
	if err != nil {
		return nil, err
	}
	err = db.Ping()
	if err == nil {
		return db, nil
	}
	if v, ok := err.(*mysql.MySQLError); ok && v.Number == 1049 {
		db, err = sql.Open("mysql", config.getDataSource())
		if err == nil {
			err = db.Ping()
			if err == nil {
				_, err = db.Exec(fmt.Sprintf("create database if not exists %s character set utf8;", config.SqlDatabaseName))
				if err == nil {
					db, err = sql.Open("mysql", config.getDataSourceName())
					if err == nil {
						return db, nil
					}
				}
			}
		}
	}
	return nil, err
}
